package edu.biwu.response;/**
 * @author 王俊彪
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet("/resp/download01")
public class RespDownload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String fileName = request.getParameter("fileName");
        System.out.println(fileName);
        //如果文件名是中文，必须对中文文件名进行编码，才能保证浏览器正常解析
        String newFileName = URLEncoder.encode(fileName, "UTF-8");
        String mimeType = getServletContext().getMimeType(fileName);
        response.setHeader("Content-Type",mimeType);
        System.out.println(mimeType);
        //这个头表示告诉浏览器，该文件是一个附件，并显示文件名
        response.setHeader("Content-Disposition","attachment;filename="+newFileName);
        InputStream is = getServletContext().getResourceAsStream("/download/"+fileName);
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        while ((b=bis.read())!=-1){
            bos.write(b);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
